package com.spic.business.alarm.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.spic.business.alarm.domain.AlarmWindDamage;
import com.spic.business.alarm.domain.FloodAlarm;
import com.spic.business.alarm.domain.IocWindDamageVo;
import com.spic.business.alarm.domain.WeatherDataModel;
import com.spic.business.alarm.domain.WindDamage;
import com.spic.business.alarm.mapper.FangPiLaoAlarmMapper;
import com.spic.business.alarm.mapper.WeatherDataMapper;
import com.spic.business.alarm.service.WeatherDataService;
import com.spic.business.alarm.service.WindDamageService;
import com.spic.business.blast.domain.vo.PresetVo;
import com.spic.business.enumconst.BusinessType;
import com.spic.business.hik.constant.HkConstant;
import com.spic.business.hik.service.HkSafeService;
import com.spic.business.preset_point.domain.PresetsPosition;
import com.spic.business.preset_point.service.IPresetsPositionService;
import com.spic.business.two.tickets.general.domain.WindConfigModel;
import com.spic.business.two.tickets.general.service.IWindConfigService;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.web.controller.BaseController;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.core.web.page.TableDataInfo;
import com.spic.system.api.RemoteStatus;
import com.spic.system.api.domain.BusinessStatus;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.apache.commons.math3.util.Pair;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * WindDamageController
 *
 * @author xuxiaochang@chinasofi.com
 * @date 2022/3/17
 */
@RestController
@RequestMapping("/windDamage")
public class WindDamageController extends BaseController {
    @Autowired
    private WindDamageService windDamageService;

    @Autowired
    private WeatherDataService weatherDataService;

    @Autowired
    private RemoteStatus remoteStatus;

    @Autowired
    private IPresetsPositionService ipresetsPositionService;

    @Autowired
    private HkSafeService hkService;

    @Autowired
    private IWindConfigService windConfigService;

    @Autowired
    private WeatherDataMapper weatherDataMapper;

    @Autowired
    private FangPiLaoAlarmMapper fangPiLaoAlarmMapper;

    @GetMapping("/list")
    public TableDataInfo list(AlarmWindDamage alarmWindDamage) {
        startPage();
        List<AlarmWindDamage> list = windDamageService.selectWindAlarmList(alarmWindDamage);
        return getDataTable(list);
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(windDamageService.selectWindDamageById(id));
    }

    @GetMapping("/job")
    public AjaxResult windDamage() {
        WeatherDataModel wind = weatherDataService.getNewestOne();
        LocalDateTime localDateTime = LocalDateTime.now();
        String today = localDateTime.withHour(0).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        String today = "2022-03-09 00:00:00";
        if (wind != null && wind.getWindRate() != null & wind.getWindRate() >= 0f) {
            List<WindDamage> list = windDamageService.selectTodayUnfinishedWork(wind.getWindRate().intValue(), today);
            if (list != null && list.size() > 0) {
                List<String> keys = list.stream().map(WindDamage::getBusinessKey).collect(Collectors.toList());
                R<List<BusinessStatus>> statusList = remoteStatus.getStateBybusinessIds(BusinessType.MAINTENANCE.getBusinessType(), keys);
                List<BusinessStatus> statuses = statusList.getData();
                //查询当天未完成的高空工作票，安许可工作时间去做
                List<String> unfinshed = statuses.stream().filter(item -> item.getStatus() != 3)
                        .map(item -> item.getBusinessKey()).collect(Collectors.toList());
                List<WindDamage> unfinishedAlarm = list.stream().filter(item -> unfinshed.contains(item.getBusinessKey())).collect(Collectors.toList());
                //插入报警数据库
                windDamageService.inserAlarm(unfinishedAlarm, wind.getWindRate());

            }
            return AjaxResult.success(list);
        }
        return AjaxResult.success(new ArrayList());
    }

    @GetMapping("oneWorld4wind")
    public AjaxResult getOneWorld4wind() {
        WeatherDataModel wind = weatherDataService.getNewestOne();
        Float windLevel = wind.getWindRate();
        List<WindConfigModel> windConfigModels = windConfigService.windConfigModelList();
        StringBuilder sp = new StringBuilder();
        for (int i = 0; i < windConfigModels.size(); i++) {
            WindConfigModel windConfigModel = windConfigModels.get(i);
            if (windLevel >= windConfigModel.getWindLevelNormal()) {
                sp.append(windConfigModel.getAlertDescription());
            }
        }
        if (StringUtils.isBlank(sp)) {
            return AjaxResult.success("当前风力级别正常，可进行高空作业。");
        }
        return AjaxResult.success(sp.toString());
    }

    @GetMapping("future7DayTickets")
    public AjaxResult future7DayTickets() {
        WeatherDataModel wind = weatherDataService.getNewestOne();
        LocalDateTime localDateTime = LocalDateTime.now();
//        String today = "2022-03-09 00:00:00";
        String today = localDateTime.withHour(0).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        int windLevel = wind.getWindRate().intValue();
        List<WindDamage> list = windDamageService.selectTodayUnfinishedWork(windLevel, today);
        if (list != null && list.size() > 0) {
            IocWindDamageVo iocWindDamageVo = new IocWindDamageVo();
            iocWindDamageVo.setWindLevel(windLevel);
            iocWindDamageVo.setWindDamages(list);
            return AjaxResult.success(iocWindDamageVo);
        } else {
            IocWindDamageVo iocWindDamageVo = new IocWindDamageVo();
            iocWindDamageVo.setWindLevel(windLevel);
            WindDamage windDamage = new WindDamage();
            windDamage.setWorkName("未来7天暂无工作票");
            iocWindDamageVo.setWindDamages(Lists.newArrayList(windDamage));
            return AjaxResult.success(iocWindDamageVo);
        }
    }

    @GetMapping("getAlarmState")
    public AjaxResult getAlarmState() {
        WeatherDataModel wind = weatherDataService.getNewestOne();
        LocalDateTime localDateTime = LocalDateTime.now();
        String today = localDateTime.withHour(0).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        int windLevel = wind.getWindRate().intValue();
        List<WindDamage> list = windDamageService.selectTodayUnfinishedWork(windLevel, today);
        List<FloodAlarm> listFlood = fangPiLaoAlarmMapper.selectFloodAlarmList(DateUtils.getZeroDateTime());
        JSONObject jsonObject = new JSONObject();
        int windCount = (list != null && list.size() > 0) ? list.size() : 0;
        int floodCount = (listFlood != null && listFlood.size() > 0) ? listFlood.size() : 0;
        int all = (windCount > 0 || floodCount > 0) ? 1 : 0;
        jsonObject.put("total", all);
        jsonObject.put("wind", windCount);
        jsonObject.put("flood", floodCount);
        return AjaxResult.success(jsonObject);
    }

    /**
     * 风害3D地图根据 经纬度 调距离最近的预置点
     *
     * @param lon
     * @param lat
     * @return
     */
    @GetMapping("getResetIdByJwd")
    public AjaxResult getResetIdByJwd(double lon, double lat) {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        Point point = geometryFactory.createPoint(new Coordinate(lon, lat));
        final String cameraIndex = HkConstant.HK_CAMERAINDEXCODE;
        //获取摄像头的预置点的经纬度等信息
        PresetsPosition presetsPosition = new PresetsPosition();
        presetsPosition.setParentId(cameraIndex);
        List<PresetsPosition> presetList = ipresetsPositionService.selectPresetsPositionList(presetsPosition);
        List<PresetsPosition> presets = presetList.stream().filter(item -> !"0".equals(item.getParentId())).collect(Collectors.toList());
        //获取最近的预置点坐标
        List<Pair<String, Double>> distList = new ArrayList<>();
        for (int i = 0; i < presets.size(); i++) {
            PresetsPosition postion = presets.get(i);
            Point setPoint = geometryFactory.createPoint(new Coordinate(Double.valueOf(postion.getLongitude()), Double.valueOf(postion.getLatitude())));
            Pair<String, Double> pair = new Pair(postion.getPresetPointindex(), setPoint.distance(point));
            distList.add(pair);
        }
        Optional<Pair<String, Double>> minDist = distList.stream().sorted(Comparator.comparing(t -> t.getValue())).findFirst();
        PresetVo presetVo = new PresetVo();
        presetVo.setCameraIndexCode(cameraIndex);
        presetVo.setPresetIndex(minDist.get().getKey());
        //设置摄像头预置点
        Map<String, Object> params = new HashMap();
        params.put("cameraIndexCode", cameraIndex);
        params.put("action", "0");
        params.put("command", "GOTO_PRESET");
        params.put("speed", "15");
        params.put("presetIndex", minDist.get().getKey());
        hkService.controlling(params);
        return AjaxResult.success();
    }

}
